var __SCROLL_LISTENER_CALLBACKS__ = new Map();
var __SCROLL_LISTENER_ENABLE__ = false;
function enableScrollListener() {
    if (__SCROLL_LISTENER_ENABLE__) {
        return;
    }
    __SCROLL_LISTENER_ENABLE__ = true;
    var jWindow = $(window);
    jWindow.unbind().on('scroll', function() {
        __SCROLL_LISTENER_CALLBACKS__.forEach(function(callback) {
            $.isFunction(callback) && callback(jWindow);
        });
    });
}
function setScrollListener(key, callback) {
    __SCROLL_LISTENER_CALLBACKS__.set(key, callback);
}
function removeScrollListener(key) {
    __SCROLL_LISTENER_CALLBACKS__.delete(key);
}
var __RESIZE_LISTENER_CALLBACKS__ = new Map();
var __RESIZE_LISTENER_ENABLE__ = false;
function enableResizeListener() {
    if (__RESIZE_LISTENER_ENABLE__) {
        return;
    }
    __RESIZE_LISTENER_ENABLE__ = true;
    var jWindow = $(window);
    jWindow.unbind().on('reize', function() {
        __RESIZE_LISTENER_CALLBACKS__.forEach(function(callback) {
            $.isFunction(callback) && callback(jWindow);
        });
    });
}
function setResizeListener(key, callback) {
    __RESIZE_LISTENER_CALLBACKS__.set(key, callback);
}
function removeResizeListener(key) {
    __RESIZE_LISTENER_CALLBACKS__.delete(key);
}




// 面板切换导航
function eventNavigationPanel(options) {
    var defaultOptions = {
        event: false,
        eventTargetElement: null,
        firstPanelElement: null,
        secondPanelElement: null,
        finishCallback: function() {}
    };
    var opts = $.extend(defaultOptions, options);

    if (opts.event) {
        // 前进
        opts.firstPanelElement.removeClass('mp-panel-visible');
        opts.secondPanelElement.addClass('mp-panel-visible');
        opts.finishCallback(
            opts.firstPanelElement,
            opts.secondPanelElement
        );
    } else {
        if (opts.eventTargetElement) {
            // 代理事件前进
            opts.eventTargetElement.click(function() {
                opts.firstPanelElement.removeClass('mp-panel-visible');
                opts.secondPanelElement.addClass('mp-panel-visible');
                opts.finishCallback(
                    opts.firstPanelElement,
                    opts.secondPanelElement,
                    opts.eventTargetElement
                );
            });
        } else {
            // 后退
            opts.firstPanelElement.addClass('mp-panel-visible');
            opts.secondPanelElement.removeClass('mp-panel-visible');
            opts.finishCallback(
                opts.firstPanelElement,
                opts.secondPanelElement
            );
        }
    }
}

function eventNavigationForwordNow(firstPanelElement, secondPanelElement, finishCallback) {
    eventNavigationPanel({
        event: true,
        firstPanelElement: firstPanelElement,
        secondPanelElement: secondPanelElement,
        finishCallback: finishCallback
    });
}

// 面板切换导航.确认事件
function eventNavigationSubmit(firstPanelElement, secondPanelElement, callback) {
    $('.mp-submit', secondPanelElement).unbind().click(function() {
        if (!callback) {
            eventNavigationPanel({
                firstPanelElement: firstPanelElement,
                secondPanelElement: secondPanelElement,
                finishCallback: function(firstPanelElement, secondPanelElement) {
                }
            });
        } else if (callback()) {
            eventNavigationPanel({
                firstPanelElement: firstPanelElement,
                secondPanelElement: secondPanelElement,
                finishCallback: function(firstPanelElement, secondPanelElement) {
                }
            });
        }
    });
}

// 面板切换导航.取消事件
function eventNavigationCancel(firstPanelElement, secondPanelElement, callback) {
    $('.mp-cancel', secondPanelElement).unbind().click(function() {
        eventNavigationPanel({
            firstPanelElement: firstPanelElement,
            secondPanelElement: secondPanelElement,
            finishCallback: function(firstPanelElement, secondPanelElement) {
                callback && callback();
            }
        });
    });
}

// 构建素材列表
function buildMaterialViewList(options) {
    var defaultOptions = {
        content: null,
        list: [],
        markIcon: '<img class="mp-remove" src="theme/images/icon-remove.png">'
    };
    var opts = $.extend(defaultOptions, options);

    var list = opts.list;
    var rowElement = $('<div class="row"/>');
    var listContentElement = $('<div class="col-xs-12"/>').appendTo(rowElement);
    if (!list || list.length == 0) {
        opts.content.empty().append(rowElement);
        return;
    }
    list.forEach(function(m) {
        var block = $('<div class="mp-box-block">');
        block.data(m);
        if (opts.markIcon) {
            block.append(
                $('<div class="mp-box-top-toolbar"/>')
                    .append(
                        $(opts.markIcon)
                            .data(m)
                            .click(function() {
                                // var img = $(this);
                                // var m = img.data();
                                // Apis.deleteResImage({uid: m.uid, type: 0}, function(response) {
                                //     img.closest('.mp-box-block').remove();
                                // });
                            })
                    )
            );
        }
        block.append(
            $('<div class="mp-image-box"/>').append(
                $('<img class="img-rounded mp-image" data-holder-rendered="true"/>')
                    .data(m)
                    .attr('onerror', 'this.src="theme/images/preview.png"')
                    .attr('alt', m.name)
                    .attr('src', m.url)
            )
        );
        block.append(
            $('<div class="mp-name"/>').append((function() {
                var value = [
                    m.file,
                    m.name,
                    moment(m.created).format('YYYY-MM-DD HH:mm:ss')
                ];
                return value.join('<br />');
            })())
        );

        block.appendTo(listContentElement);
    });

    opts.content.empty().append(rowElement);

}

var MPDialogCache = {
    selectImageMaterial: null,
    selectVideoMaterial: null
};

var MPDialog = {

    // sk-mask
    // open / close
    waiting: function(status) {
        if (status == 'open' || status == true) {
            $('.sk-mask').fadeIn('fast');
            $('body').css('overflow', 'hidden');
            return;
        }
        $('.sk-mask').fadeOut('fast');
        $('body').css('overflow', '');
    },

    openWaiting: function(status) {
        MPDialog.waiting(true);
    },

    closeWaiting: function(status) {
        MPDialog.waiting();
    },

    // mp-panel-dialog-message-confirm
    alert: function(options) {
        var defaultOptions = {
            message: '消息',
            confirmText: '确认',
            cancelText: '取消',
            showCancel: false,
            confirmCallback: function() {},
            cancelCallback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        MPDialog.confirm(opts);
    },

    // mp-panel-dialog-message-confirm
    confirm: function(options) {
        var defaultOptions = {
            message: '消息',
            confirmText: '确认',
            cancelText: '取消',
            showCancel: true,
            confirmCallback: function() {},
            cancelCallback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-message-confirm').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();
        $('.mp-message-content', panel).html(opts.message);
        $('.mp-submit', panel)
            .click(function() {
                opts.confirmCallback && opts.confirmCallback();
                mask.remove();
                panel.remove();
            })
            .html(opts.confirmText);
        $('.mp-cancel', panel)
            .click(function() {
                opts.cancelCallback && opts.cancelCallback();
                mask.remove();
                panel.remove();
            })
            .html(opts.cancelText);
        if (opts.showCancel == false) {
            $('.mp-cancel', panel).hide();
        } else {
            $('.mp-cancel', panel).show();
        }
    },

    // mp-panel-dialog-select-material-image
    selectImageMaterial: function(options) {
        var defaultOptions = {
            cache: 'clean', // clean, apply
            siteId: '',
            lang: '',
            confirmText: '选择',
            cancelText: '取消',
            confirmCallback: function(data) {},
            cancelCallback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-select-material-image').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.cache == 'clean') {
            MPDialogCache.selectImageMaterial = null;
        } else if (opts.cache == 'apply') {
            if (MPDialogCache.selectImageMaterial) {
                $('[name="name"]', panel).val(MPDialogCache.selectImageMaterial.name);
            }
        }
        var pageIndex = 0;
        var pageSize = 100;
        var search;
        var build = function(response) {

            var page = Pagination({
                pageStart: pageIndex,
                pageSize: pageSize,
                totalSize: response.data.totalCount
            }, function(index) {
                pageIndex = index;
                search();
            });
            $('.pagination', panel).parent().empty()
                .append(page);

            var list = response.data ? response.data.forms : [];

            var content = $('.mp-panel-content', panel);
            buildMaterialViewList({
                content: content,
                list: list,
                markIcon: '<img class="mp-remove" src="theme/images/icon-selected-rect.png">'
            });
            $('.mp-image-box', content).click(function(e) {
                var block = $(this).closest('.mp-box-block');
                if (block.hasClass('mp-selected')) {
                    block.removeClass('mp-selected')
                        .find('.mp-remove').attr('src', 'theme/images/icon-selected-rect.png');
                } else {
                    // $('.mp-selected .mp-remove', content).attr('src', 'theme/images/icon-selected-rect.png');
                    // $('.mp-selected', content).removeClass('mp-selected');
                    block.addClass('mp-selected')
                        .find('.mp-remove').attr('src', 'theme/images/icon-selected-rect-high.png');
                }

            });
        };

        search = function() {
            var condition = formValue($('form', panel));
            MPDialogCache.selectImageMaterial = condition;
            condition.siteId = opts.siteId;
            condition.lang =  opts.lang;
            condition.pageStart = pageIndex * pageSize;
            condition.pageSize = pageSize;
            if (condition.name) {
                Apis.getResImagesSearch(condition, function(response) {
                    build(response);
                });
            } else {
                Apis.getResImages(condition, function(response) {
                    build(response);
                });
            }
        };
        search();

        var sortCreateAt = $('.mp-sort-by-create_at', panel);
        var sortName = $('.mp-sort-by-name', panel);
        sortCreateAt.unbind().click(function() {
            sortName.removeClass('mp-sort-selected').find('.iconfont').remove();
            sortCreateAt.addClass('mp-sort-selected').find('.iconfont').remove();
            var ascOrDes = sortCreateAt.data('order');
            if (ascOrDes == 'desc') {
                ascOrDes = true;
                sortCreateAt.attr('order', 'asc');
                sortCreateAt.data('order', 'asc');
                sortCreateAt.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
            } else {
                ascOrDes = false;
                sortCreateAt.attr('order', 'desc');
                sortCreateAt.data('order', 'desc');
                sortCreateAt.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
            }
            var orders = [
                {
                    field: 'create_at',
                    ascOrDes: ascOrDes
                }
            ];

            pageIndex = 0;
            pageSize = 100;
            var condition = formValue($('form', panel));
            condition.siteId = App.getSiteId();
            condition.lang = App.getLang();
            condition.pageStart = pageIndex * pageSize;
            condition.pageSize = pageSize;
            condition.orders = orders;
            if (condition.name) {
                Apis.getResImagesSearch(condition, function(response) {
                    build(response);
                });
            } else {
                Apis.getResImages(condition, function(response) {
                    build(response);
                });
            }
        });
        sortName.unbind().click(function() {
            sortName.addClass('mp-sort-selected').find('.iconfont').remove();
            sortCreateAt.removeClass('mp-sort-selected').find('.iconfont').remove();
            var ascOrDes = sortName.data('order');
            if (ascOrDes == 'desc') {
                ascOrDes = true;
                sortName.attr('order', 'asc');
                sortName.data('order', 'asc');
                sortName.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
            } else {
                ascOrDes = false;
                sortName.attr('order', 'desc');
                sortName.data('order', 'desc');
                sortName.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
            }
            var orders = [
                {
                    field: 'name',
                    ascOrDes: ascOrDes
                }
            ];

            pageIndex = 0;
            pageSize = 100;
            var condition = formValue($('form', panel));
            condition.siteId = App.getSiteId();
            condition.lang = App.getLang();
            condition.pageStart = pageIndex * pageSize;
            condition.pageSize = pageSize;
            condition.orders = orders;
            if (condition.name) {
                Apis.getResImagesSearch(condition, function(response) {
                    build(response);
                });
            } else {
                Apis.getResImages(condition, function(response) {
                    build(response);
                });
            }
        });

        $('.mp-search', panel).click(search);
        $('.mp-upload-button', panel).click(function() {
            MPDialog.materialUploadImage({
                callback: function() {
                    search();
                }
            });
        });
        $('.mp-submit', panel)
            .click(function() {
                var list = [];
                $('.mp-box-block.mp-selected', panel).each(function(i, block) {
                    list.push($(block).data());
                });
                opts.confirmCallback && opts.confirmCallback(list);
                mask.remove();
                panel.remove();
            })
            .html(opts.confirmText);
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });
    },

    // mp-panel-dialog-select-material-video
    selectVideoMaterial: function(options) {
        var defaultOptions = {
            cache: 'clean', // clean, apply
            siteId: '',
            lang: '',
            confirmText: '选择',
            cancelText: '取消',
            confirmCallback: function(data) {},
            cancelCallback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-select-material-video').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.cache == 'clean') {
            MPDialogCache.selectVideoMaterial = null;
        } else if (opts.cache == 'apply') {
            if (MPDialogCache.selectVideoMaterial) {
                $('[name="name"]', panel).val(MPDialogCache.selectVideoMaterial.name);
            }
        }

        var build = function(list) {
            var content = $('.mp-panel-content', panel);
            buildMaterialViewList({
                content: content,
                list: list.map(function(m) {
                    m.url = 'theme/images/preview-video.png';
                    return m;
                }),
                markIcon: '<img class="mp-remove" src="theme/images/icon-selected-rect.png">'
            });
            $('.mp-image-box', content).click(function(e) {
                var block = $(this).closest('.mp-box-block');
                if (block.hasClass('mp-selected')) {
                    block.removeClass('mp-selected')
                        .find('.mp-remove').attr('src', 'theme/images/icon-selected-rect.png');
                } else {
                    // $('.mp-selected .mp-remove', content).attr('src', 'theme/images/icon-selected-rect.png');
                    // $('.mp-selected', content).removeClass('mp-selected');
                    block.addClass('mp-selected')
                        .find('.mp-remove').attr('src', 'theme/images/icon-selected-rect-high.png');
                }
            });

            // 缩略图
            var images = $('.mp-image', content);
            var count = images.length;
            var index = 0;
            var ci = new Chain();
            images.each(function() {
                ci.method(function(next, _) {
                    var m = $(images[index]).data();
                    new VideoScreenshot({
                        url: m.playurl,
                        type: 'video/mp4',
                        image: images[index],
                        callback: function(base64image) {
                            // $('<img id="m-image" width="500" />')
                            //     .attr('src', base64image)
                            //     .css('display', 'block')
                            //     .appendTo(listElement);
                        }
                    });
                    index++;
                    next();
                });
            });
            ci.method(function() {
                runVideoScreenshotQueue();
            })
            ci.start();
        };

        var search = function() {
            var condition = formValue($('form', panel));
            MPDialogCache.selectVideoMaterial = condition;
            condition.siteId = opts.siteId;
            condition.lang =  opts.lang;
            condition.pageStart = 0;
            condition.pageSize = 100;
            if (condition.name) {
                Apis.getResVideosSearch(condition, function(response) {
                    build(response.data ? response.data.forms : []);
                });
            } else {
                Apis.getResVideos(condition, function(response) {
                    build(response.data ? response.data.forms : []);
                });
            }
        };
        search();

        var sortCreateAt = $('.mp-sort-by-create_at', panel);
        var sortName = $('.mp-sort-by-name', panel);
        sortCreateAt.unbind().click(function() {
            sortName.removeClass('mp-sort-selected').find('.iconfont').remove();
            sortCreateAt.addClass('mp-sort-selected').find('.iconfont').remove();
            var ascOrDes = sortCreateAt.data('order');
            if (ascOrDes == 'desc') {
                ascOrDes = true;
                sortCreateAt.attr('order', 'asc');
                sortCreateAt.data('order', 'asc');
                sortCreateAt.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
            } else {
                ascOrDes = false;
                sortCreateAt.attr('order', 'desc');
                sortCreateAt.data('order', 'desc');
                sortCreateAt.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
            }
            var orders = [
                {
                    field: 'create_at',
                    ascOrDes: ascOrDes
                }
            ];

            var condition = formValue($('form', panel));
            condition.siteId = App.getSiteId();
            condition.lang = App.getLang();
            condition.pageStart = 0;
            condition.pageSize = 100;
            condition.orders = orders;
            if (condition.name) {
                Apis.getResVideosSearch(condition, function(response) {
                    build(response.data ? response.data.forms : []);
                });
            } else {
                Apis.getResVideos(condition, function(response) {
                    build(response.data ? response.data.forms : []);
                });
            }
        });
        sortName.unbind().click(function() {
            sortName.addClass('mp-sort-selected').find('.iconfont').remove();
            sortCreateAt.removeClass('mp-sort-selected').find('.iconfont').remove();
            var ascOrDes = sortName.data('order');
            if (ascOrDes == 'desc') {
                ascOrDes = true;
                sortName.attr('order', 'asc');
                sortName.data('order', 'asc');
                sortName.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
            } else {
                ascOrDes = false;
                sortName.attr('order', 'desc');
                sortName.data('order', 'desc');
                sortName.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
            }
            var orders = [
                {
                    field: 'name',
                    ascOrDes: ascOrDes
                }
            ];

            var condition = formValue($('form', panel));
            condition.siteId = App.getSiteId();
            condition.lang = App.getLang();
            condition.pageStart = 0;
            condition.pageSize = 100;
            condition.orders = orders;
            if (condition.name) {
                Apis.getResVideosSearch(condition, function(response) {
                    build(response.data ? response.data.forms : []);
                });
            } else {
                Apis.getResVideos(condition, function(response) {
                    build(response.data ? response.data.forms : []);
                });
            }
        });

        $('.mp-search', panel).click(search);
        $('.mp-upload-button', panel).click(function() {
            MPDialog.materialUploadVideo({
                callback: function() {
                    search();
                }
            });
        });
        $('.mp-submit', panel)
            .click(function() {
                var list = [];
                $('.mp-box-block.mp-selected', panel).each(function(i, block) {
                    list.push($(block).data());
                });
                opts.confirmCallback && opts.confirmCallback(list);
                mask.remove();
                panel.remove();
            })
            .html(opts.confirmText);
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });
    },

    // mp-panel-dialog-preview
    preview: function(options) {
        var defaultOptions = {
            content: function(build) {build('')}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-preview').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();
        opts.content(function(content) {
            $('.mp-preview-content', panel).html(content);
        });
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });
    },

    // mp-panel-dialog-select-article
    selectArticle: function(options) {
        var defaultOptions = {
            siteId: '',
            lang: '',
            confirmText: '选择',
            cancelText: '取消',
            confirmCallback: function(data) {},
            cancelCallback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-select-article').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        var build = function(list) {
            var content = $('table tbody', panel).empty();
            list.forEach(function(m) {
                var row = $('<tr/>').appendTo(content);
                row.data('value', m);
                $('<td/>').html((function() {
                    var checkbox = $('<input type="checkbox" />').data(m);
                    // checkbox.change(function(e) {
                    //     $('input[type="checkbox"]', panel).each(function(i, box) {
                    //         if (box != e.target) {
                    //             box.checked = false;
                    //         }
                    //     });
                    // });
                    return checkbox;
                })()).appendTo(row);
                $('<td/>').html(m.articleNo).appendTo(row);
                $('<td/>').html(m.title).appendTo(row);
                $('<td/>').html(m.updateBy ? m.updateBy : '').appendTo(row);
                $('<td/>').html((function() {
                    var v = m.updateAt;
                    if (m.updateAt) {
                        return moment(v).format('YYYY-MM-DD HH:mm:ss');
                    }
                    return '';
                })()).appendTo(row);
            });
        };

        var search = function(pageIndex, orders) {
            var pageSize = 10;
            var condition = formValue($('form', panel));
            condition.articleNo = condition.articleNo ? condition.articleNo : null;
            condition.title = condition.title ? condition.title : null;
            condition.userId = condition.userId ? condition.userId : null;
            condition.siteId = opts.siteId;
            condition.lang = opts.lang;
            condition.pageSize = pageSize;
            condition.pageStart = pageIndex ? (pageIndex * pageSize) : 0;
            condition.detail = false;
            if (orders) {
                condition.orders = orders;
            }
            Apis.getArticleList(condition, function(response) {
                build(response.data ? response.data.articles : []);
                var page = Pagination({
                    pageStart: pageIndex,
                    pageSize: condition.pageSize,
                    totalSize: response.data.totalSize
                }, function(index) {
                    search(index, orders);
                });
                $('.pagination', panel).parent().empty()
                    .append(page);
            });
        };
        search(0);

        var sortArticleNo = $('.mp-sort-by-article_no', panel);
        var sortUpdateAt = $('.mp-sort-by-update_at', panel);
        sortArticleNo.unbind().click(function() {
            sortUpdateAt.removeClass('mp-sort-selected').find('.iconfont').remove();
            sortArticleNo.addClass('mp-sort-selected').find('.iconfont').remove();
            var ascOrDes = sortArticleNo.data('order');
            if (ascOrDes == 'desc') {
                ascOrDes = true;
                sortArticleNo.attr('order', 'asc');
                sortArticleNo.data('order', 'asc');
                sortArticleNo.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortArticleNo).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
            } else {
                ascOrDes = false;
                sortArticleNo.attr('order', 'desc');
                sortArticleNo.data('order', 'desc');
                sortArticleNo.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortArticleNo).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
            }
            var orders = [
                {
                    field: 'a.article_no',
                    ascOrDes: ascOrDes
                }
            ];

            search(0, orders);
        });
        sortUpdateAt.unbind().click(function() {
            sortUpdateAt.addClass('mp-sort-selected').find('.iconfont').remove();
            sortArticleNo.removeClass('mp-sort-selected').find('.iconfont').remove();
            var ascOrDes = sortUpdateAt.data('order');
            if (ascOrDes == 'desc') {
                ascOrDes = true;
                sortUpdateAt.attr('order', 'asc');
                sortUpdateAt.data('order', 'asc');
                sortUpdateAt.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortUpdateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
            } else {
                ascOrDes = false;
                sortUpdateAt.attr('order', 'desc');
                sortUpdateAt.data('order', 'desc');
                sortUpdateAt.append('<i class="icon iconfont"></i>');
                $('.iconfont', sortUpdateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
            }
            var orders = [
                {
                    field: 'a.update_at',
                    ascOrDes: ascOrDes
                }
            ];

            search(0, orders);
        });

        $('.mp-search', panel).click(function() {
            search(0);
        });
        $('.mp-submit', panel)
            .click(function() {
                var list = [];
                $('input[type="checkbox"]:checked', panel).each(function(i, box) {
                    list.push($(box).data());
                });
                opts.confirmCallback && opts.confirmCallback(list);
                mask.remove();
                panel.remove();
            })
            .html(opts.confirmText);
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });
    },

    // mp-panel-dialog-material-upload-image
    materialUploadImage: function(options) {
        var defaultOptions = {
            callback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-material-upload-image').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        var formJqObj = $('form:first', panel);
        var reset = function() {
            $('.mp-upload', formJqObj).unbind().hide();
            // 解除禁止
            $('.fileinput-button', formJqObj).show();
            // $('.mp-file-input', formJqObj).show();
            // $('.mp-file-input', formJqObj).closest('.fileinput-button').removeAttr('disabled');
            $('[name="name"]', formJqObj).removeAttr('readonly');
            // 还原
            formJqObj[0].reset();
            $('.mp-upload-status', formJqObj).html('<code style="color: blue;">{0}</code>'.format('未选择图片'));
        };
        reset();

        // 上传组件
        var fileInputJqObj = $('.mp-file-input', panel);
        // /resource/{siteId}/{lang}/{type}
        var url = '/support/resource/{0}/{1}/image/upload'.format(App.getSiteId(), App.getLang());
        fcloud({
            url: url,
            fileInputJqObj: fileInputJqObj,
            formJqObj: formJqObj,
            submitCallback: function(data) {
                // 已选择图片
                var files = data.files.map(function(m) {
                    return m.name;
                }).join(', ');
                $('[name="name"]', formJqObj).val(files);
                $('.mp-upload-status', formJqObj).html('<code style="color: blue;">{0}{1}</code>'.format('已选择图片: ', files));
                $('.fileinput-button', formJqObj).hide();
                $('.mp-upload', panel).unbind().click(function() {
                    Apis.isResExist({
                        siteId: App.getSiteId(),
                        lang: App.getLang(),
                        type: 'image',
                        name: $('[name="name"]', formJqObj).val()
                    }, function(response) {
                        if (response.data == 0) {
                            // 没有重复, 开始上传
                        	data.files[0].name = encodeURI(data.files[0].name);
                            data.submit();
                            // 禁止操作
                            // $('.mp-file-input', formJqObj).hide();
                            // $('.mp-file-input', formJqObj).closest('.fileinput-button').attr('disabled', 'disabled');
                            $('[name="name"]', formJqObj).attr('readonly', 'readonly');
                        } else {
                            // 有重复, 确认是否覆盖
                            MPDialog.confirm({
                                message: '已有重复名称的素材, 是否覆盖?',
                                confirmText: '覆盖',
                                cancelText: '取消',
                                confirmCallback: function() {
                                    data.submit();
                                    // 禁止操作
                                    // $('.mp-file-input', formJqObj).hide();
                                    // $('.mp-file-input', formJqObj).closest('.fileinput-button').attr('disabled', 'disabled');
                                    $('[name="name"]', formJqObj).attr('readonly', 'readonly');
                                }
                            });
                        }
                    });
                }).show();
                $('.mp-image', panel).attr('src', 'theme/images/preview.png');
            },
            progressCallback: function(uniqueId, progress) {
                // 上传进度
                $('.mp-upload-status', formJqObj).html('<code style="color: green;">{0}</code>'.format('已上传: ' + progress + '%'));
            },
            doneCallback: function(uniqueId, response) {
                // 上传完成
                reset();
                // if (result.url) {
                    $('.mp-upload-status', formJqObj).html('<code style="color: green;">{0}</code>'.format('上传成功，可继续选择'));
                // } else {
                //     $('.mp-upload-status', formJqObj).html('<code style="color: red;">{0}</code>'.format('上传失败，请重新选择'));
                // }

                // 预览
                var result = null;
                if ($.isArray(response)) {
                    result = response[0].data;
                } else {
                    result = response.data;
                }
                // result
                // /resource/image/2018-06-17/2
                // $('.mp-image', panel).attr('src', result.url.concat('/download'));
                $('.mp-image', panel).attr('src', result.url);
            }
        });

        $('.mp-cancel', panel)
            .click(function() {
                opts.callback && opts.callback();
                mask.remove();
                panel.remove();
            });
    },

    // mp-panel-dialog-material-upload-video
    materialUploadVideo: function(options) {
        var defaultOptions = {
            callback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-material-upload-video').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        var formJqObj = $('form:first', panel);
        var reset = function() {
            $('.mp-upload', formJqObj).unbind().hide();
            // 解除禁止
            $('.fileinput-button', formJqObj).show();
            // $('.mp-file-input', formJqObj).show();
            // $('.mp-file-input', formJqObj).closest('.fileinput-button').removeAttr('disabled');
            $('[name="name"]', formJqObj).removeAttr('readonly');
            // 还原
            formJqObj[0].reset();
            $('.mp-upload-status', formJqObj).html('<code style="color: blue;">{0}</code>'.format('未选择视频'));
        };
        reset();

        // 上传组件
        var fileInputJqObj = $('.mp-file-input', panel);
        // /resource/{siteId}/{lang}/{type}
        var url = '/support/resource/{0}/{1}/video/upload'.format(App.getSiteId(), App.getLang());
        fcloud({
            url: url,
            fileInputJqObj: fileInputJqObj,
            formJqObj: formJqObj,
            submitCallback: function(data) {
                // 已选择图片
                var files = data.files.map(function(m) {
                    return m.name;
                }).join(', ');
                $('[name="name"]', formJqObj).val(files);
                $('.mp-upload-status', formJqObj).html('<code style="color: blue;">{0}{1}</code>'.format('已选择视频: ', files));
                $('.fileinput-button', formJqObj).hide();
                $('.mp-upload', panel).unbind().click(function() {
                    Apis.isResExist({
                        siteId: App.getSiteId(),
                        lang: App.getLang(),
                        type: 'video',
                        name: $('[name="name"]', formJqObj).val()
                    }, function(response) {
                        if (response.data == 0) {
                            // 没有重复, 开始上传
                            data.submit();
                            // 禁止操作
                            // $('.mp-file-input', formJqObj).hide();
                            // $('.mp-file-input', formJqObj).closest('.fileinput-button').attr('disabled', 'disabled');
                            $('[name="name"]', formJqObj).attr('readonly', 'readonly');
                        } else {
                            // 有重复, 确认是否覆盖
                            MPDialog.confirm({
                                message: '已有重复名称的素材, 是否覆盖?',
                                confirmText: '覆盖',
                                cancelText: '取消',
                                confirmCallback: function() {
                                    data.submit();
                                    // 禁止操作
                                    // $('.mp-file-input', formJqObj).hide();
                                    // $('.mp-file-input', formJqObj).closest('.fileinput-button').attr('disabled', 'disabled');
                                    $('[name="name"]', formJqObj).attr('readonly', 'readonly');
                                }
                            });
                        }
                    });
                }).show();
                // $('.img-thumbnail', panel).attr('src', 'theme/images/preview-video.png');
            },
            progressCallback: function(uniqueId, progress) {
                // 上传进度
                $('.mp-upload-status', formJqObj).html('<code style="color: green;">{0}</code>'.format('已上传: ' + progress + '%'));
            },
            doneCallback: function(uniqueId, response) {
                // 上传完成
                reset();
                // if (result.url) {
                $('.mp-upload-status', formJqObj).html('<code style="color: green;">{0}</code>'.format('上传成功，可继续选择'));
                // } else {
                //     $('.mp-upload-status', formJqObj).html('<code style="color: red;">{0}</code>'.format('上传失败，请重新选择'));
                // }

                // 预览
                var result = null;
                if ($.isArray(response)) {
                    result = response[0].data;
                } else {
                    result = response.data;
                }
                // result
                // /resource/image/2018-06-17/2
                // $('.img-thumbnail', secondPanelElement).attr('src', result.url);
            }
        });

        $('.mp-cancel', panel)
            .click(function() {
                opts.callback && opts.callback();
                mask.remove();
                panel.remove();
            });
    },


    // mp-panel-dialog-import-upload-excel
    importUploadExcel: function(options) {
        var defaultOptions = {
            siteId: App.getSiteId(),
            lang: App.getLang(),
            callback: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-import-upload-excel').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        var formJqObj = $('form:first', panel);
        var reset = function() {
            $('.mp-upload', formJqObj).unbind().hide();
            // 解除禁止
            $('.fileinput-button', formJqObj).show();
            // $('.mp-file-input', formJqObj).show();
            // $('.mp-file-input', formJqObj).closest('.fileinput-button').removeAttr('disabled');
            $('[name="name"]', formJqObj).removeAttr('readonly');
            // 还原
            formJqObj[0].reset();
            $('.mp-upload-status', formJqObj).html('<code style="color: blue;">{0}</code>'.format('未选择文件'));
        };
        reset();

        // 上传组件
        var fileInputJqObj = $('.mp-file-input', panel);
        var url = '/support/resource/{0}/{1}/excel/upload'.format(opts.siteId, App.getLang());
        fcloud({
            url: url,
            fileInputJqObj: fileInputJqObj,
            formJqObj: formJqObj,
            submitCallback: function(data) {
                // 已选择图片
                var files = data.files.map(function(m) {
                    return m.name;
                }).join(', ');
                $('[name="name"]', formJqObj).val(files);
                $('.mp-upload-status', formJqObj).html('<code style="color: blue;">{0}{1}</code>'.format('已选择文件: ', files));
                $('.fileinput-button', formJqObj).hide();
                $('.mp-upload', panel).unbind().click(function() {
                    // 确认是否上传
                    MPDialog.confirm({
                        message: '确定上传?',
                        confirmText: '上传',
                        cancelText: '取消',
                        confirmCallback: function() {
                            data.submit();
                            // 禁止操作
                            // $('.mp-file-input', formJqObj).hide();
                            // $('.mp-file-input', formJqObj).closest('.fileinput-button').attr('disabled', 'disabled');
                            $('[name="name"]', formJqObj).attr('readonly', 'readonly');
                        }
                    });
                }).show();
                // $('.img-thumbnail', panel).attr('src', 'theme/images/preview-video.png');
            },
            progressCallback: function(uniqueId, progress) {
                // 上传进度
                $('.mp-upload-status', formJqObj).html('<code style="color: green;">{0}</code>'.format('已上传: ' + progress + '%'));
            },
            doneCallback: function(uniqueId, response) {
                // 上传完成
                reset();
                if (response.status != 200) {
                    if (response.message) {
                        MPDialog.alert({
                            message: response.message,
                            confirmCallback: function() {

                            }
                        });
                    }
                }
                // if (result.url) {
                // $('.mp-upload-status', formJqObj).html('<code style="color: green;">{0}</code>'.format('上传成功，可继续选择'));
                // } else {
                //     $('.mp-upload-status', formJqObj).html('<code style="color: red;">{0}</code>'.format('上传失败，请重新选择'));
                // }

                // 预览
                // var result = null;
                // if ($.isArray(response)) {
                //     result = response[0].data;
                // } else {
                //     result = response.data;
                // }
                // result
                // /resource/image/2018-06-17/2
                // $('.img-thumbnail', secondPanelElement).attr('src', result.url);
            }
        });

        $('.mp-cancel', panel)
            .click(function() {
                opts.callback && opts.callback();
                mask.remove();
                panel.remove();
            });
    },

    // mp-panel-dialog-append-category
    categoryAppend: function(options) {
        var defaultOptions = {
            data: null,
            // data: {
            //     id: '',
            //     category: '',
            //     name: '',
            //     sort: ''
            // },
            content: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-append-category').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.data) {
            $('.mp-panel-title a', panel).html('修改分类');
        } else {
            $('.mp-panel-title a', panel).html('添加分类');
        }

        if (App.getLang() == 'zhCN') {
            $('.t-mode-normal', panel).hide();
            $('.t-mode-multi-lang', panel).show();
        } else {
            $('.t-mode-normal', panel).show();
            $('.t-mode-multi-lang', panel).hide();
        }

        // $('div.mp-select2', panel).remove();
        // $('select.mp-select2', panel)
        //     .removeClass('select2-offscreen')
        //     .removeAttr('tabindex');
        // App.initSelect2(panel);
        // $('.select2-drop:last').css('z-index', 99999);
        //
        $('.mp-submit', panel)
            .click(function() {
                var value = formValue($('form', panel));
                var siteId = App.getSiteId();
                if (App.getLang() == 'zhCN') {
                    if (!$.trim(value.zhCN)/* &&
                        !$.trim(value.jaJP) &&
                        !$.trim(value.enUS) &&
                        !$.trim(value.zhTW) &&
                        !$.trim(value.ko) &&
                        !$.trim(value.th)*/) {
                        return false;
                    }

                    if (!$.trim(value.sort)) {
                        value.sort = '0';
                    }

                    if (opts.data) {
                        var parameter = {
                            siteId: siteId,
                            type: 1, // Item(0), Category(1), Hot(2);
                            cnForm: {
                                id: value.zhCNId,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'zhCN',
                                type: 1,
                                name: value.zhCN,
                                sort: value.zhCNSort
                            },
                            jpForm: {
                                id: value.jaJPId,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'jaJP',
                                type: 1,
                                name: value.jaJP,
                                sort: value.jaJPSort
                            },
                            enForm: {
                                id: value.enUSId,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'enUS',
                                type: 1,
                                name: value.enUS,
                                sort: value.enUSSort
                            },
                            twForm: {
                                id: value.zhTWId,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'zhTW',
                                type: 1,
                                name: value.zhTW,
                                sort: value.zhTWSort
                            },
                            krForm: {
                                id: value.koId,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'ko',
                                type: 1,
                                name: value.ko,
                                sort: value.koSort
                            },
                            thForm: {
                                id: value.thId,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'th',
                                type: 1,
                                name: value.th,
                                sort: value.thSort
                            }
                        };
                        Apis.createFolderLangAll(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        var parameter = {
                            siteId: siteId,
                            type: 1, // Item(0), Category(1), Hot(2);
                            cnForm: {
                                id: 0,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'zhCN',
                                type: 1,
                                name: value.zhCN,
                                sort: value.zhCNSort
                            },
                            jpForm: {
                                id: 0,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'jaJP',
                                type: 1,
                                name: value.jaJP,
                                sort: value.jaJPSort
                            },
                            enForm: {
                                id: 0,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'enUS',
                                type: 1,
                                name: value.enUS,
                                sort: value.enUSSort
                            },
                            twForm: {
                                id: 0,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'zhTW',
                                type: 1,
                                name: value.zhTW,
                                sort: value.zhTWSort
                            },
                            krForm: {
                                id: 0,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'ko',
                                type: 1,
                                name: value.ko,
                                sort: value.koSort
                            },
                            thForm: {
                                id: 0,
                                siteId: siteId,
                                itemId: value.itemId,
                                lang: 'th',
                                type: 1,
                                name: value.th,
                                sort: value.thSort
                            }
                        };
                        Apis.createFolderLangAll(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }
                } else {
                    if (!$.trim(value.name)) {
                        return false;
                    }
                    if (opts.data) {
                        var parameter = {
                            id: opts.data.id,
                            name: value.name,
                            itemId: value.itemId,
                            type: 1, // Item(0), Category(1), Hot(2);
                            sort: value.sort,
                        };
                        Apis.updateFolder(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        var parameter = {
                            siteId: App.getSiteId(),
                            lang: App.getLang(),
                            name: value.name,
                            itemId: value.itemId,
                            type: 1, // Item(0), Category(1), Hot(2);
                            sort: value.sort,
                        };
                        Apis.createFolder(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }
                }

            });
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });

        $('[name="itemId"]', panel)
            .attr('data-o-item-id', opts.data ? opts.data.itemId : '')
            .attr('data-o-sort', opts.data ? opts.data.sort : '')
            .change(function() {
                var oItemId = $(this).data('oItemId');
                var oSort   = $(this).data('oSort');
                var itemId  = this.value;
                if (itemId == oItemId) {
                    $('form [name="sort"]', panel).val(oSort);
                    $('form [name="zhCNSort"]', panel).val(oSort);
                    $('form [name="jaJPSort"]', panel).val(oSort);
                    $('form [name="enUSSort"]', panel).val(oSort);
                    $('form [name="zhTWSort"]', panel).val(oSort);
                    $('form [name="koSort"]', panel).val(oSort);
                    $('form [name="thSort"]', panel).val(oSort);
                } else {
                    $('form [name="sort"]', panel).val(FolderCacheMap[itemId].length);
                    $('form [name="zhCNSort"]', panel).val(FolderCacheMap[itemId].length);
                    $('form [name="jaJPSort"]', panel).val(FolderCacheMap[itemId].length);
                    $('form [name="enUSSort"]', panel).val(FolderCacheMap[itemId].length);
                    $('form [name="zhTWSort"]', panel).val(FolderCacheMap[itemId].length);
                    $('form [name="koSort"]', panel).val(FolderCacheMap[itemId].length);
                    $('form [name="thSort"]', panel).val(FolderCacheMap[itemId].length);
                }
            });

        var init = new Chain();
        init.method(function(next, _) {

            FolderTypeList = [];
            FolderTypeMap = {};
            FolderCacheMap = {};

            var condition = {};
            condition.lang = App.getLang();
            condition.siteId = App.getSiteId();
            condition.folderType = 0;
            Apis.getFolders(condition, function(response) {
                var list = response.data.folders;
                var select = $('[name="itemId"]', panel).empty();
                select.append('<option value="">请选择</option>');
                list.forEach(function(folder) {
                    FolderTypeList.push(folder.id);
                    FolderTypeMap[folder.id] = folder.name;
                    FolderCacheMap[folder.id] = [];
                    $('<option/>')
                        .attr('value', folder.id)
                        .html(folder.name)
                        .appendTo(select);
                });
                $('div.mp-select2', panel).remove();
                $('select.mp-select2', panel)
                    .removeClass('select2-offscreen')
                    .removeAttr('tabindex');
                App.initSelect2(panel);
                $('.select2-drop:last').css('z-index', 99999);
                next();
            });
        });
        init.method(function(next, _) {
            // 显示原始值
            if (opts.data) {
                $('form [name="itemId"]', panel).val(opts.data.itemId).change();
                $('form [name="name"]', panel).val(opts.data.name);
                $('form [name="sort"]', panel).val(opts.data.sort);
                if (App.getLang() == 'zhCN') {
                    var parameter = {
                        siteId: App.getSiteId(),
                        folderType: 1,
                        lang: App.getLang(),
                        id: opts.data.id
                    };
                    Apis.getFolderLangAll(parameter, function(response) {
                        var list = response.data;
                        list.forEach(function(m) {
                            var lang = m.language;
                            $('form [name="' + lang + '"]', panel).val(m.name);
                            $('form [name="' + lang + 'Id"]', panel).val(m.id);
                        });
                    });
                }
            }
            next();
        });
        init.start();

    },

    // mp-panel-dialog-tag-category-append
    tagCategoryAppend: function(options) {
        var defaultOptions = {
            data: null,
            // data: {
            //     id: '',
            //     category: '',
            //     name: '',
            //     sort: ''
            // },
            content: function() {},
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-tag-category-append').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.data) {
            $('.mp-panel-title a', panel).html('修改标签分类');
        } else {
            $('.mp-panel-title a', panel).html('添加标签分类');
        }

        if (App.getLang() == 'zhCN') {
            $('.t-mode-normal', panel).hide();
            $('.t-mode-multi-lang', panel).show();
        } else {
            $('.t-mode-normal', panel).show();
            $('.t-mode-multi-lang', panel).hide();
        }

        $('.mp-submit', panel)
            .click(function() {
                var value = formValue($('form', panel));
                var siteId = App.getSiteId();
                if (App.getLang() == 'zhCN') {
                    if (!$.trim(value.zhCN)/* &&
                        !$.trim(value.jaJP) &&
                        !$.trim(value.enUS) &&
                        !$.trim(value.zhTW) &&
                        !$.trim(value.ko) &&
                        !$.trim(value.th)*/) {
                        return false;
                    }
                    if (opts.data) {
                        var parameter = {
                            siteId: siteId,
                            forms: []
                        };
                        ['zhCN', 'enUS', 'jaJP', 'zhTW', 'ko', 'th'].forEach(function(lang) {
                            parameter.forms.push({
                                id: value[lang + 'Id'],
                                name: value[lang],
                                lang: lang,
                                siteId: siteId
                            });
                        });
                        Apis.addTagCategotyLangAll(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        var parameter = {
                            siteId: siteId,
                            forms: []
                        };
                        ['zhCN', 'enUS', 'jaJP', 'zhTW', 'ko', 'th'].forEach(function(lang) {
                            parameter.forms.push({
                                id: 0,
                                name: value[lang],
                                lang: lang,
                                siteId: siteId
                            });
                        });
                        Apis.addTagCategotyLangAll(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }

                } else {
                    if (!$.trim(value.name)) {
                        return false;
                    }
                    if (opts.data) {
                        var parameter = {
                            id: opts.data.id,
                            name: value.name,
                        };
                        Apis.updTagCategoty(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        var parameter = {
                            siteId: App.getSiteId(),
                            lang: App.getLang(),
                            name: value.name,
                        };
                        Apis.addTagCategoty(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }
                }

            });
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });

        // 显示原始值
        if (opts.data) {
            $('form [name="name"]', panel).val(opts.data.name);
            if (App.getLang() == 'zhCN') {
                var parameter = {
                    siteId: App.getSiteId(),
                    lang: App.getLang(),
                    id: opts.data.id
                };
                Apis.getTagCategotyLangAll(parameter, function(response) {
                    var list = response.data;
                    list.forEach(function(m) {
                        var lang = m.lang;
                        $('form [name="' + lang + '"]', panel).val(m.name);
                        $('form [name="' + lang + 'Id"]', panel).val(m.id);
                    });
                });
            }
        }

    },

    //　mp-panel-dialog-append-tag
    tagAppend: function(options) {
        var defaultOptions = {
            data: null,
            // data: {
            //     id: '',
            //     category: '',
            //     name: '',
            //     sort: ''
            // },
            content: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-append-tag').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.data) {
            $('.mp-panel-title a', panel).html('修改标签');
        } else {
            $('.mp-panel-title a', panel).html('添加标签');
        }

        if (App.getLang() == 'zhCN') {
            $('.t-mode-normal', panel).hide();
            $('.t-mode-multi-lang', panel).show();
        } else {
            $('.t-mode-normal', panel).show();
            $('.t-mode-multi-lang', panel).hide();
        }

        $('div.mp-select2', panel).remove();
        $('select.mp-select2', panel)
            .removeClass('select2-offscreen')
            .removeAttr('tabindex');
        App.initSelect2(panel);
        $('.select2-drop:last').css('z-index', 99999);
        $('.mp-submit', panel)
            .click(function() {
                var value = formValue($('form', panel));
                var siteId = App.getSiteId();
                if (App.getLang() == 'zhCN') {
                    if (!$.trim(value.zhCN) /*&&
                        !$.trim(value.jaJP) &&
                        !$.trim(value.enUS) &&
                        !$.trim(value.zhTW) &&
                        !$.trim(value.ko) &&
                        !$.trim(value.th) */||
                        !$.trim(value.tagCatId)) {
                        return false;
                    }
                    if (opts.data) {
                        var parameter = {
                            siteId: siteId,
                            lang: App.getLang(),
                            tagcatId: value.tagCatId,
                            forms: []
                        };
                        ['zhCN', 'enUS', 'jaJP', 'zhTW', 'ko', 'th'].forEach(function(lang) {
                            parameter.forms.push({
                                id: value[lang + 'Id'],
                                tag: value[lang],
                                lang: lang,
                                tagcatId: value.tagCatId,
                                siteId: siteId
                            });
                        });
                        Apis.addTagLangAll(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        var parameter = {
                            siteId: siteId,
                            lang: App.getLang(),
                            tagcatId: value.tagCatId,
                            forms: []
                        };
                        ['zhCN', 'enUS', 'jaJP', 'zhTW', 'ko', 'th'].forEach(function(lang) {
                            parameter.forms.push({
                                id: 0,
                                tag: value[lang],
                                lang: lang,
                                tagcatId: value.tagCatId,
                                siteId: siteId
                            });
                        });
                        Apis.addTagLangAll(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }
                } else {
                    if (!$.trim(value.name)
                        || !$.trim(value.tagCatId)) {
                        return false;
                    }
                    if (opts.data) {
                        var parameter = {
                            id: opts.data.id,
                            name: value.name
                        };
                        Apis.updTag(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        var parameter = {
                            siteId: App.getSiteId(),
                            lang: App.getLang(),
                            name: value.name,
                            tagCatId: value.tagCatId
                        };
                        Apis.addTag(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }
                }

            });
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });

        var siteId = App.getSiteId();
        var select = $('form [name="tagCatId"]', panel);
        selectOptionsForTagCatLog(siteId, select, function() {
            // 显示原始值
            if (opts.data) {
                $('form [name="tagCatId"]', panel).val(opts.data.catalog.id).change().attr('readonly', 'readonly');
                $('form [name="name"]', panel).val(opts.data.name);
                if (App.getLang() == 'zhCN') {
                    var parameter = {
                        siteId: App.getSiteId(),
                        lang: App.getLang(),
                        tagcatId: opts.data.catalog.id,
                        id: opts.data.id
                    };
                    Apis.getTagLangAll(parameter, function(response) {
                        var list = response.data;
                        list.forEach(function(m) {
                            var lang = m.lang;
                            $('form [name="' + lang + '"]', panel).val(m.name);
                            $('form [name="' + lang + 'Id"]', panel).val(m.id);
                        });
                    });
                }
            }
        });
    },

    //　mp-panel-dialog-append-users
    userAppend: function(options) {
        var defaultOptions = {
            mode: null,
            data: null,
            // data: {
            //     id: '',
            //     category: '',
            //     name: '',
            //     sort: ''
            // },
            content: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-append-users').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.data) {
            $('.mp-panel-title a', panel).html('修改用户');
        } else {
            $('.mp-panel-title a', panel).html('添加用户');
        }

        var buildTask = new Chain();
        buildTask.method(function (next, _) {
            var condition = {};
            condition.lang = App.getLang();
            condition.siteId = App.getSiteId();
            Apis.getDomains(condition, function(response) {
                $('div.mp-select2', panel).remove();
                $('select.mp-select2', panel)
                    .removeClass('select2-offscreen')
                    .removeAttr('tabindex');
                var select = $('[name="siteId"]', panel).empty();
                response.data.forEach(function(m) {
                    $('<option/>')
                        .attr('value', m.id)
                        .html(m.siteName)
                        .appendTo(select);
                });
                App.initSelect2(panel);
                $('.select2-drop').css('z-index', 99999);
                select.change();
                next();
            });
        });
        buildTask.method(function (next, _) {

            $('.mp-submit', panel)
                .click(function() {
                    var value = formValue($('form', panel));
                    if (opts.data) {
                        if (!$.trim(value.userName)
                            || !$.trim(value.loginName)
                            || !$.trim(value.siteId)
                            || !$.trim(value.role)) {
                            return false;
                        }
                        var parameter = {
                            uid: opts.data.uid,
                            loginName: opts.data.loginName,
                            userName: value.userName,
                            password: (value.password ? value.password : opts.data.password),
                            siteId: value.siteId,
                            role: value.role
                        };
                        Apis.updateAccount(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    } else {
                        if (!$.trim(value.userName)
                            || !$.trim(value.loginName)
                            || !value.password
                            || !$.trim(value.siteId)
                            || !$.trim(value.role)) {
                            return false;
                        }
                        var parameter = {
                            loginName: value.loginName,
                            userName: value.userName,
                            password: value.password,
                            siteId: value.siteId,
                            role: value.role
                        };
                        Apis.createAccount(parameter, function() {
                            opts.confirmCallback && opts.confirmCallback();
                            mask.remove();
                            panel.remove();
                        });
                    }
                });
            $('.mp-cancel', panel)
                .click(function() {
                    mask.remove();
                    panel.remove();
                });

            // 显示原始值
            if (opts.data) {
                $('form [name="loginName"]', panel).val(opts.data.loginName).attr('readonly', 'readonly');
                $('form [name="userName"]', panel).val(opts.data.userName);
                $('form [name="password"]', panel).val('');
                $('form [name="role"]', panel).val(opts.data.role).change();
                if (opts.data.siteId > 0) {
                    $('form [name="siteId"]', panel).val(opts.data.siteId).change();
                }
            }
            if (opts.mode == 'current') {
                $('form [name="role"]', panel)
                    .attr('disabled', 'disabled');
                $('form [name="siteId"]', panel)
                    .attr('disabled', 'disabled');
            } else {
                $('form [name="role"]', panel)
                    .removeAttr('disabled', 'disabled');
                $('form [name="siteId"]', panel)
                    .removeAttr('disabled', 'disabled');
            }
        });
        buildTask.start();
    },

    //　mp-panel-dialog-user-password
    userPassword: function(options) {
        var defaultOptions = {

        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-user-password').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        $('.mp-panel-title a', panel).html('修改密码');

        $('.mp-submit', panel)
            .click(function() {
                var value = formValue($('form', panel));
                // if (!$.trim(value.loginName)
                //     || !value.password
                //     || !value.confirm) {
                //     return false;
                // }
                if (!value.password) {
                    MPDialog.alert({
                        message: '请输入密码'
                    });
                    return false;
                }
                if (!value.confirm) {
                    MPDialog.alert({
                        message: '请输入确认密码'
                    });
                    return false;
                }
                if (value.password != value.confirm) {
                    MPDialog.alert({
                        message: '确认密码与密码不一致'
                    });
                    return false;
                }
                var userInfo = App.getUserInfo();
                var parameter = {
                    uid: userInfo.uid,
                    loginName: userInfo.loginName,
                    userName: userInfo.userName,
                    password: value.password,
                    siteId: userInfo.siteId,
                    role: userInfo.role
                };
                Apis.updateAccount(parameter, function() {
                    opts.confirmCallback && opts.confirmCallback();
                    mask.remove();
                    panel.remove();
                });
            });
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });

        // 显示原始值
        var userInfo = App.getUserInfo();
        $('form [name="loginName"]', panel).val(userInfo.loginName).attr('readonly', 'readonly');

        // if (opts.data) {
        //     $('form [name="loginName"]', panel).val(opts.data.loginName).attr('readonly', 'readonly');
        //     $('form [name="userName"]', panel).val(opts.data.userName);
        //     $('form [name="password"]', panel).val('');
        //     $('form [name="role"]', panel).val(opts.data.role).change();
        //     if (opts.data.siteId > 0) {
        //         $('form [name="siteId"]', panel).val(opts.data.siteId).change();
        //     }
        // }
        // if (opts.mode == 'current') {
        //     $('form [name="role"]', panel)
        //         .attr('disabled', 'disabled');
        //     $('form [name="siteId"]', panel)
        //         .attr('disabled', 'disabled');
        // } else {
        //     $('form [name="role"]', panel)
        //         .removeAttr('disabled', 'disabled');
        //     $('form [name="siteId"]', panel)
        //         .removeAttr('disabled', 'disabled');
        // }
    },

    //　mp-panel-dialog-append-domain
    domainAppend: function(options) {
        var defaultOptions = {
            data: null,
            // data: {
            //     id: '',
            //     category: '',
            //     name: '',
            //     sort: ''
            // },
            content: function() {}
        };
        var opts = $.extend(defaultOptions, options);
        var mask = $('<div class="mp-panel-dialog-mask"/>').appendTo('body');
        var html = $('.mp-panel-dialog-append-domain').closest('.mp-hide-html').html();
        var panel = $(html).appendTo('body').show();

        if (opts.data) {
            $('.mp-panel-title a', panel).html('修改网站');
        } else {
            $('.mp-panel-title a', panel).html('添加网站');
        }

        $('.mp-submit', panel)
            .click(function() {
                var value = formValue($('form', panel));
                if (opts.data) {
                    // if (!$.trim(value.siteName)
                    //     || !$.trim(value.siteUrl)) {
                    //     return false;
                    // }
                    // var parameter = {
                    //     uid: opts.data.uid,
                    //     siteName: opts.data.siteName,
                    //     siteUrl: value.siteUrl,
                    // };
                    // Apis.updateAccount(parameter, function() {
                    //     opts.confirmCallback && opts.confirmCallback();
                    //     mask.remove();
                    //     panel.remove();
                    // });
                } else {
                    if (!$.trim(value.siteName)
                        || !$.trim(value.siteUrl)) {
                        return false;
                    }
                    var parameter = {
                        name: value.siteName,
                        url: value.siteUrl,
                        description: value.siteName,
                    };
                    Apis.createDomain(parameter, function() {
                        opts.confirmCallback && opts.confirmCallback();
                        mask.remove();
                        panel.remove();
                    });
                }
            });
        $('.mp-cancel', panel)
            .click(function() {
                mask.remove();
                panel.remove();
            });

        // 显示原始值
        if (opts.data) {
            $('form [name="siteName"]', panel).val(opts.data.siteName);
            $('form [name="siteUrl"]', panel).val(opts.data.siteUrl);
        }
    },
};



// 创建编辑器
function MPEditor(options) {
    var defaultOptions = {
        id: null,
        title: null,
        content: null,
        onSelectionChangeEvent: function(ueEditor) {}
    };
    var opts = $.extend(defaultOptions, options);

    var ueEditor = null;

    this.getOpts = function() {
        return opts;
    };

    this.element = function() {
        var html = $('<div/>');
        if (opts.title) {
            var title = $('<div class="row"/>').appendTo(html)
                .append(
                    $('<div class="col-xs-12 mp-editor-title"/>')
                        .append(
                            $('<label>标题</label>').html(opts.title)
                        )
                );
        }
        var editor = $('<div class="row"/>').appendTo(html)
            .append(
                $('<div class="col-xs-12"/>')
                    .append(
                        $('<script name="content" type="text/plain"><p></p></script>')
                            .attr('id', opts.id)
                            .html((function() {
                                return opts.content ? opts.content : '<p></p>';
                            })())
                    )
            );
        return html;
    };

    this.init = function() {
        ueEditor = UE.getEditor(opts.id, {
            toolbars: [
                ['undo', 'redo', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'imagenone', 'imageleft', 'imagecenter', 'imageright', 'link', 'unlink'],
                [
                    'indent',
                    'justifyleft', //居左对齐
                    'justifyright', //居右对齐
                    'justifycenter', //居中对齐
                    'justifyjustify', //两端对齐
                    'forecolor', //字体颜色
                    'backcolor', //背景色
                ]
            ],
            autoHeightEnabled: true,
            autoFloatEnabled: true,
            elementPathEnabled: false
        });
        ueEditor.addListener('selectionchange',function(){
            opts.onSelectionChangeEvent && opts.onSelectionChangeEvent(ueEditor);
        });
        return ueEditor;
    };

    this.getCache = function() {
        return {
            id: opts.id,
            content: ueEditor.getContent()
        };
    };

    this.setContent = function(content) {
        UE.getEditor(opts.id).setContent(content);
    };

    this.destroy = function() {
        ueEditor.destroy();
        $('#' + opts.id).remove();
    };
}



function Pagination(options, clickCallback) {
    var defaultOptions = {
        pageStart: 0,
        pageSize: 10,
        totalSize: 0
    };
    var opts = $.extend(defaultOptions, options);
    var page = Math.floor(opts.totalSize / opts.pageSize) + ((opts.totalSize % opts.pageSize) > 0 ? 1 : 0);

    var pIndex = opts.pageStart;
    var sliceBegin = pIndex - 5;
    var sliceEnd = pIndex + 5 + 1;
    var maxIndex = page - 1;

    if (sliceBegin < 0) {
        sliceEnd += Math.abs(sliceBegin);
        sliceBegin = 0;
    }

    var list = [];
    for (var i = 0 ; i < page ; ++ i) {
        list.push(i);
    }

    console.log('pagination info:', 'opts', opts);
    console.log('pagination info:', 'page', page);
    console.log('pagination info:', 'pIndex', pIndex);
    // console.log('pagination info:', 'sliceBegin', sliceBegin);
    // console.log('pagination info:', 'sliceEnd', sliceEnd);

    var element = $('<ul class="pagination"/>');
    element.append('<li><a href="javascript:void(0);" aria-label="First" data-index="0"><span aria-hidden="true">首页</span></a></li>');
    // element.append('<li><a href="javascript:void(0);" aria-label="Previous" data-index="0"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span></a></li>');
    element.append(
        $('<li/>')
            .append(
                $('<a href="javascript:void(0);" aria-label="Previous"/>')
                    .attr('data-index', (function() {
                        if (opts.pageStart - 1 < 0) {
                            return 0;
                        }
                        return opts.pageStart - 1;
                    })())
                    .html('<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>')
            )
    );
    list.slice(sliceBegin, sliceEnd).forEach(function(m, i) {
        if (m === opts.pageStart) {
            element.append(
                $('<li/>')
                    .append(
                        $('<a href="javascript:void(0);" class="page-on" style="font-weight: bold;"/>')
                            .attr('data-index', m).html(m + 1)
                    )
            );
        } else {
            element.append(
                $('<li/>')
                    .append(
                        $('<a href="javascript:void(0);" class="page-on"/>')
                            .attr('data-index', m).html(m + 1)
                    )
            );
        }
    });

    element.append(
        $('<li/>')
            .append(
                $('<a href="javascript:void(0);" aria-label="Next"/>')
                    .attr('data-index', (function() {
                        if (opts.pageStart + 1 > maxIndex) {
                            return -1;
                        }
                        return opts.pageStart + 1;
                    })())
                    .html('<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>')
            )
    );

    if (opts.pageStart < maxIndex) {
        // element.append('<li><a href="javascript:void(0);" aria-label="Last"><span aria-hidden="true">尾页</span></a></li>');
        element.append(
            $('<li/>')
                .append(
                    $('<a href="javascript:void(0);" aria-label="Next"/>')
                        .attr('data-index', (function() {
                            return maxIndex;
                        })())
                        .html('<span aria-hidden="true">尾页</span></a>')
                )
        );
    } else {
        // element.append('<li><a href="javascript:void(0);" aria-label="Last"><span aria-hidden="true">尾页</span></a></li>');
        element.append(
            $('<li/>')
                .append(
                    $('<a href="javascript:void(0);" aria-label="Next"/>')
                        .attr('data-index', -1)
                        .html('<span aria-hidden="true">尾页</span></a>')
                )
        );
    }

    $('a', element).click(function(e) {
        var index = $(this).data('index');
        console.log('pagination index:', index);
        if (index == -1) {
            return;
        }
        clickCallback(index);
    });
    return element;
}

// 视频截图
var VideoScreenshotQueue = [];
function runVideoScreenshotQueue() {
    var index = 0;
    var length = VideoScreenshotQueue.length;
    var stream = new Chain();
    VideoScreenshotQueue.forEach(function() {
        stream.method(function(next, _) {
            var task = VideoScreenshotQueue[index++];
            var opts = task.opts;
            var hidden = task.hidden;
            var video = task.video;
            // video.onplay = function() {
            //     console.log('onplay');
            // };
            video.onplaying = function() {
                // console.log('onplaying');
                // video.pause();
                var canvas = document.createElement('canvas');
                canvas.width = this.videoWidth;
                canvas.height = this.videoHeight;
                var context = canvas.getContext('2d');
                context.drawImage(this, 0, 0, this.videoWidth, this.videoHeight);
                if (opts.image) {
                    $(opts.image).attr('src', canvas.toDataURL('image/png'));
                }
                opts.callback(canvas.toDataURL('image/png'));
                hidden.remove();

            };
            video.play();
            next();
        });
    });
    stream.method(function(next, _) {
        VideoScreenshotQueue = [];
    });
    stream.start();
}
function VideoScreenshot(options) {
    var defaultOptions = {
        id: '',
        url: 'video url',
        type: 'video type',
        image: null,
        callback: function(base64image) {}
    };
    var opts = $.extend(defaultOptions, options);
    var hidden = $('<div style="display: none;"/>').appendTo('body');
    var videoElement = $('<video preload="preload" />').appendTo(hidden);
    var video = videoElement[0];
    video.muted = true;
    $('<source/>')
        .attr('src', opts.url)
        .attr('type', opts.type)
        .appendTo(videoElement);
    // video.play();
    // video.onplay = function() {
    //     setTimeout(function() {
    //         video.pause();
    //         var canvas = document.createElement('canvas');
    //         canvas.width = video.videoWidth;
    //         canvas.height = video.videoHeight;
    //         var context = canvas.getContext('2d');
    //         context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    //         if (opts.image) {
    //             $(opts.image).attr('src', canvas.toDataURL('image/png'));
    //         }
    //         opts.callback(canvas.toDataURL('image/png'));
    //         hidden.remove();
    //     }, 100);
    // };
    VideoScreenshotQueue.push({
        opts: opts,
        video: video,
        hidden: hidden,
    });
}